package com.nf.health.app.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.MainActivity;
import com.nf.health.app.utils.AppUtil;
import com.nf.health.app.utils.FileHelper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadService extends Service {

	public static final String BUNDLE_KEY_DOWNLOAD_URL = "download_url";
	public static final String BUNDLE_KEY_TITLE = "title";
	protected static final int NOTIFY_ID = 0;
	private Context mContext = this;
	private String saveFileName = Constants.DOWNLOADPath;
	private Runnable downloadRunnable = new Runnable() {
		public void run() {
			File file = new File(Constants.DOWNLOADPath);
			if (!file.exists()) {
				file.mkdirs();
			}
			String apkFile = saveFileName;
			File saveFile = new File(apkFile);
			try {
				downloadUpdateFile(downloadUrl, saveFile);
			} catch (Exception e) {
				e.printStackTrace();
				mHandler.sendEmptyMessage(2);
			}
		}

	};
	private String mTitle = "正在下载";
	private Handler mHandler = new Handler() {


		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				// 下载完毕
				mNotificationManager.cancel(NOTIFY_ID);
				File file = new File(saveFileName);
				if(!file.exists()){
					return;
				}
				AppUtil.installAPK(getApplicationContext(), file);
				break;
			case 2:
				// 取消通知
				mNotificationManager.cancel(NOTIFY_ID);
				break;
			case 1:
				int rate = msg.arg1;
				if (rate <= 100) {
					RemoteViews contentview = mNotification.contentView;
					contentview.setTextViewText(R.id.tv_download_state, mTitle + "(" + rate+ "%" + ")");
					contentview.setProgressBar(R.id.pb_download, 100, rate, false);
					if(rate == 100){
						// 下载完毕后变换通知形式
						mNotification.flags = Notification.FLAG_AUTO_CANCEL;
						mNotification.contentView = null;
						Intent intent = new Intent(mContext, MainActivity.class);
						// 告知已完成
						intent.putExtra("completed", "yes");
						// 更新参数,注意flags要使用FLAG_UPDATE_CURRENT
						PendingIntent contentIntent = PendingIntent.getActivity(
								mContext, 0, intent,
								PendingIntent.FLAG_UPDATE_CURRENT);
//						mNotification.setLatestEventInfo(mContext, "下载完成",
//								"文件已下载完毕", contentIntent);
						mNotification.tickerText="下载完成";
//						serviceIsDestroy = true;
						stopSelf();// 停掉服务自身
					}
				}
				mNotificationManager.notify(NOTIFY_ID, mNotification);
				break;
			}
		}
	};
	private NotificationManager mNotificationManager;
	private String downloadUrl;
	private Notification mNotification;
	@Override
	public void onCreate() {
		super.onCreate();
		
		mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		downloadUrl = intent.getStringExtra(BUNDLE_KEY_DOWNLOAD_URL);
		saveFileName = saveFileName+FileHelper.getFilePath(downloadUrl);
		return new DownloadBinder();
	}

	
	public class DownloadBinder extends Binder{
		
		public void start(){
			setUpdateNotification();
			downloadApk();
		}
		
		public void cancelNotification() {
			mHandler.sendEmptyMessage(2);
		}
	}
	private void setUpdateNotification() {
		mNotification = new Notification(R.drawable.ic_launcher, "准备下载", System.currentTimeMillis());
		//设置Notification状态一直保持显示
		mNotification.flags = Notification.FLAG_ONGOING_EVENT;
		//设置内容意图
		Intent intent = new Intent(this, MainActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		mNotification.contentIntent = pendingIntent;
		//设置个性化试图
		RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_notification);
		remoteViews.setTextViewText(R.id.tv_download_state, mTitle);
		mNotification.contentView = remoteViews;
		mNotificationManager.notify(NOTIFY_ID, mNotification);
	}
	private void downloadApk() {
		Thread thread = new Thread(downloadRunnable);
		thread.start();
	}
	

	private long downloadUpdateFile(String downloadUrl, File saveFile) throws Exception {
		int downloadCount = 0;
		int currentSize = 0;
		long totalSize = 0;
		int updateTotalSize = 0;

		HttpURLConnection httpConnection = null;
		InputStream is = null;
		FileOutputStream fos = null;

		try {
			URL url = new URL(downloadUrl);
			httpConnection = (HttpURLConnection) url.openConnection();
			httpConnection.setRequestProperty("User-Agent", "PacificHttpClient");
			if (currentSize > 0) {
				httpConnection.setRequestProperty("RANGE", "bytes="+ currentSize + "-");
			}
			httpConnection.setConnectTimeout(10000);
			httpConnection.setReadTimeout(20000);
			updateTotalSize = httpConnection.getContentLength();
			if (httpConnection.getResponseCode() == 404) {
				throw new Exception("fail!");
			}
			is = httpConnection.getInputStream();
			fos = new FileOutputStream(saveFile, false);
			byte buffer[] = new byte[1024];
			int readsize = 0;
			while ((readsize = is.read(buffer)) > 0) {
				fos.write(buffer, 0, readsize);
				totalSize += readsize;
				// 为了防止频繁的通知导致应用吃紧，百分比增加10才通知一次
				if ((downloadCount == 0)
						|| (int) (totalSize * 100 / updateTotalSize) - 10 >= downloadCount) {
					downloadCount += 10;
					
					// 更新进度
					Message msg = mHandler.obtainMessage();
					msg.what = 1;
					msg.arg1 = downloadCount;
						mHandler.sendMessage(msg);
//						if (callback != null)
//							callback.OnBackResult(progress);
				}
			}
			
			// 下载完成通知安装
			mHandler.sendEmptyMessageDelayed(0,1000);
			// 下载完了，cancelled也要设置
//			canceled = true;
			
		} finally {
			if (httpConnection != null) {
				httpConnection.disconnect();
			}
			if (is != null) {
				is.close();
			}
			if (fos != null) {
				fos.close();
			}
		}
		return totalSize;
			
	}
}
